<?php

namespace App\Helpers\Lib;

use App\Exceptions\DaoException;
use App\Exceptions\ValidationException;
use App\Helpers\ResponseEnum;
use App\Models\TongOrder;
use App\Models\TongUser;
use App\Models\TongUserProfit;
use App\Models\TongUserRecharge;
use Illuminate\Support\Facades\DB;
use Yansongda\Pay\Pay;
use Yansongda\Pay\Log;

class WechatPay
{
    //        'miniapp_id' => 'wx295e8e285524ad00', // 小程序 APPID
    //        'mch_id' => '1675513863',
    //        'key' => '',
    protected $config = [
        'alipay' => [
            'default' => [
                // 必填-支付宝分配的 app_id
                'app_id' => '2016082000295641',
                // 必填-应用私钥 字符串或路径
                // 在 https://open.alipay.com/develop/manage 《应用详情->开发设置->接口加签方式》中设置
                'app_secret_cert' => 'MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCDRjOg5DnX+8L+rB8d2MbrQ30Z7JPM4hiDhawHSwQCQ7RlmQNpl6b/N6IrPLcPFC1uii179U5Il5xTZynfjkUyJjnHusqnmHskftLJDKkmGbSUFMAlOv+NlpUWMJ2A+VUopl+9FLyqcV+XgbaWizxU3LsTtt64v89iZ2iC16H6/6a3YcP+hDZUjiNGQx9cuwi9eJyykvcwhDkFPxeBxHbfwppsul+DYUyTCcl0Ltbga/mUechk5BksW6yPPwprYHQBXyM16Jc3q5HbNxh3660FyvUBFLuVWIBs6RtR2gZCa6b8rOtCkPQKhUKvzRMlgheOowXsWdk99GjxGQDK5W4XAgMBAAECggEAYPKnjlr+nRPBnnNfR5ugzH67FToyrU0M7ZT6xygPfdyijaXDb2ggXLupeGUOjIRKSSijDrjLZ7EQMkguFHvtfmvcoDTDFaL2zq0a3oALK6gwRGxOuzAnK1naINkmeOmqiqrUab+21emEv098mRGbLNEXGCgltCtz7SiRdo/pgIPZ1wHj4MH0b0K2bFG3xwr51EyaLXKYH4j6w9YAXXsTdvzcJ+eRE0Yq4uGPfkziqg8d0xXSEt90HmCGHKo4O2eh1w1IlBcHfK0F6vkeUAtrtAV01MU2bNoRU147vKFxjDOVBlY1nIZY/drsbiPMuAfSsodL0hJxGSYivbKTX4CWgQKBgQDd0MkF5AIPPdFC+fhWdNclePRw4gUkBwPTIUljMP4o+MhJNrHp0sEy0sr1mzYsOT4J20hsbw/qTnMKGdgy784bySf6/CC7lv2hHp0wyS3Es0DRJuN+aTyyONOKGvQqd8gvuQtuYJy+hkIoHygjvC3TKndX1v66f9vCr/7TS0QPywKBgQCXgVHERHP+CarSAEDG6bzI878/5yqyJVlUeVMG5OXdlwCl0GAAl4mDvfqweUawSVFE7qiSqy3Eaok8KHkYcoRlQmAefHg/C8t2PNFfNrANDdDB99f7UhqhXTdBA6DPyW02eKIaBcXjZ7jEXZzA41a/zxZydKgHvz4pUq1BdbU5ZQKBgHyqGCDgaavpQVAUL1df6X8dALzkuqDp9GNXxOgjo+ShFefX/pv8oCqRQBJTflnSfiSKAqU2skosdwlJRzIxhrQlFPxBcaAcl0VTcGL33mo7mIU0Bw2H1d4QhAuNZIbttSvlIyCQ2edWi54DDMswusyAhHxwz88/huJfiad1GLaLAoGASIweMVNuD5lleMWyPw2x3rAJRnpVUZTc37xw6340LBWgs8XCEsZ9jN4t6s9H8CZLiiyWABWEBufU6z+eLPy5NRvBlxeXJOlq9iVNRMCVMMsKybb6b1fzdI2EZdds69LSPyEozjkxdyE1sqH468xwv8xUPV5rD7qd83+pgwzwSJkCgYBrRV0OZmicfVJ7RqbWyneBG03r7ziA0WTcLdRWDnOujQ9orhrkm+EY2evhLEkkF6TOYv4QFBGSHfGJ0SwD7ghbCQC/8oBvNvuQiPWI8B+00LwyxXNrkFOxy7UfIUdUmLoLc1s/VdBHku+JEd0YmEY+p4sjmcRnlu4AlzLxkWUTTg==',
                // 必填-应用公钥证书 路径
                // 设置应用私钥后，即可下载得到以下3个证书
                'app_public_cert_path' => '/Users/yansongda/pay/cert/appCertPublicKey_2016082000295641.crt',
                // 必填-支付宝公钥证书 路径
                'alipay_public_cert_path' => '/Users/yansongda/pay/cert/alipayCertPublicKey_RSA2.crt',
                // 必填-支付宝根证书 路径
                'alipay_root_cert_path' => '/Users/yansongda/pay/cert/alipayRootCert.crt',
                'return_url' => 'https://yansongda.cn/alipay/return',
                'notify_url' => 'https://yansongda.cn/alipay/notify',
                // 选填-第三方应用授权token
                'app_auth_token' => '',
                // 选填-服务商模式下的服务商 id，当 mode 为 Pay::MODE_SERVICE 时使用该参数
                'service_provider_id' => '',
                // 选填-默认为正常模式。可选为： MODE_NORMAL, MODE_SANDBOX, MODE_SERVICE
                'mode' => Pay::MODE_NORMAL,
            ]
        ],
        'wechat' => [
            'default' => [
                // 必填-商户号，服务商模式下为服务商商户号
                // 可在 https://pay.weixin.qq.com/ 账户中心->商户信息 查看
                //'mch_id' => '1675513863',
                //'mch_id' => '1673426150',
                //'mch_id' => '1664267901',
                //'mch_id' => '1699064036',
                'mch_id' => '1700975466',
                //'mch_id' => '1704113656',
                // 选填-v2商户私钥
                //'mch_secret_key_v2' => 'dec308e678804986186b40e40b8988v2',
                //'mch_secret_key_v2' => '1hB2cD3eF4gH5iJ6kL7mN8oP9qR0sT1u',
                //'mch_secret_key_v2' => '614e28171505ed6bd989a04410a9b56d',
                //'mch_secret_key_v2' => '35772c95026698d8a5e541d7c75fd7da',
                'mch_secret_key_v2' => '757a28349787c752299ccab263b892bc',
                //'mch_secret_key_v2' => 'WXElGHf1PpjTH28RhaaPT1oJ3APLrbDM',
                // 必填-v3 商户秘钥
                // 即 API v3 密钥(32字节，形如md5值)，可在 账户中心->API安全 中设置
                //'mch_secret_key' => 'dec308e678804986186b40e40b898848',
                //'mch_secret_key' => '3hB2cD3eF4gH5iJ6kL7mN8oP9qR0sT1u',
                //'mch_secret_key' => '614e28171505ed6bd989a04410a9b5v3',
                //'mch_secret_key' => '35772c95026698d8a5e541d7c75fd7da',
                'mch_secret_key' => '757a28349787c752299ccab263b892bc',
                //'mch_secret_key' => '8qIWUP2kenWL5eixFI8ZsOaE3liJw1Pa',
                // 必填-商户私钥 字符串或路径
                // 即 API证书 PRIVATE KEY，可在 账户中心->API安全->申请API证书 里获得
                // 文件名形如：apiclient_key.pem
                //'mch_secret_cert' => '/www/wwwroot/tongxiansheng/storage/cert/apiclient_key.pem',
                'mch_secret_cert' => '/www/wwwroot/tongxiansheng_new/storage/cert/1700975466/apiclient_key.pem',
                // 必填-商户公钥证书路径
                // 即 API证书 CERTIFICATE，可在 账户中心->API安全->申请API证书 里获得
                // 文件名形如：apiclient_cert.pem
                //'mch_public_cert_path' => '/www/wwwroot/tongxiansheng/storage/cert/apiclient_cert.pem',
                'mch_public_cert_path' => '/www/wwwroot/tongxiansheng_new/storage/cert/1700975466/apiclient_cert.pem',
                // 必填-微信回调url
                // 不能有参数，如?号，空格等，否则会无法正确回调
                'notify_url' => 'https://dztxsother.19w.top/api/wechat_pay_notice',
                // 选填-公众号 的 app_id
                // 可在 mp.weixin.qq.com 设置与开发->基本配置->开发者ID(AppID) 查看
                'mp_app_id' => '2016082000291234',
                // 选填-小程序 的 app_id
                'mini_app_id' => 'wx7d18bd50f621bf1c',
                // 选填-app 的 app_id
                'app_id' => '',
                // 选填-服务商模式下，子公众号 的 app_id
                'sub_mp_app_id' => '',
                // 选填-服务商模式下，子 app 的 app_id
                'sub_app_id' => '',
                // 选填-服务商模式下，子小程序 的 app_id
                'sub_mini_app_id' => '',
                // 选填-服务商模式下，子商户id
                'sub_mch_id' => '',
                // 选填-微信平台公钥证书路径, optional，强烈建议 php-fpm 模式下配置此参数
                'wechat_public_cert_path' => [
                    //'45F59D4DABF31918AFCEC556D5D2C6E376675D57' => __DIR__.'/Cert/wechatPublicKey.crt',
                ],
                // 选填-默认为正常模式。可选为： MODE_NORMAL, MODE_SERVICE
                'mode' => Pay::MODE_NORMAL,
            ]
        ],
        'unipay' => [
            'default' => [
                // 必填-商户号
                'mch_id' => '777290058167151',
                // 选填-商户密钥：为银联条码支付综合前置平台配置：https://up.95516.com/open/openapi?code=unionpay
                'mch_secret_key' => '979da4cfccbae7923641daa5dd7047c2',
                // 必填-商户公私钥
                'mch_cert_path' => __DIR__.'/Cert/unipayAppCert.pfx',
                // 必填-商户公私钥密码
                'mch_cert_password' => '000000',
                // 必填-银联公钥证书路径
                'unipay_public_cert_path' => __DIR__.'/Cert/unipayCertPublicKey.cer',
                // 必填
                'return_url' => 'https://yansongda.cn/unipay/return',
                // 必填
                'notify_url' => 'https://yansongda.cn/unipay/notify',
                'mode' => Pay::MODE_NORMAL,
            ],
        ],
        'douyin' => [
            'default' => [
                // 选填-商户号
                // 抖音开放平台 --> 应用详情 --> 支付信息 --> 产品管理 --> 商户号
                'mch_id' => '73744242495132490630',
                // 必填-支付 Token，用于支付回调签名
                // 抖音开放平台 --> 应用详情 --> 支付信息 --> 支付设置 --> Token(令牌)
                'mch_secret_token' => 'douyin_mini_token',
                // 必填-支付 SALT，用于支付签名
                // 抖音开放平台 --> 应用详情 --> 支付信息 --> 支付设置 --> SALT
                'mch_secret_salt' => 'oDxWDBr4U7FAAQ8hnGDm29i4A6pbTMDKme4WLLvA',
                // 必填-小程序 app_id
                // 抖音开放平台 --> 应用详情 --> 支付信息 --> 支付设置 --> 小程序appid
                'mini_app_id' => 'tt226e54d3bd581bf801',
                // 选填-抖音开放平台服务商id
                'thirdparty_id' => '',
                // 选填-抖音支付回调地址
                'notify_url' => 'https://yansongda.cn/douyin/notify',
            ],
        ],
        'jsb' => [
            'default' => [
                // 服务代码
                'svr_code' => '',
                // 必填-合作商ID
                'partner_id' => '',
                // 必填-公私钥对编号
                'public_key_code' => '00',
                // 必填-商户私钥(加密签名)
                'mch_secret_cert_path' => '',
                // 必填-商户公钥证书路径(提供江苏银行进行验证签名用)
                'mch_public_cert_path' => '',
                // 必填-江苏银行的公钥(用于解密江苏银行返回的数据)
                'jsb_public_cert_path' => '',
                //支付通知地址
                'notify_url' => '',
                // 选填-默认为正常模式。可选为： MODE_NORMAL:正式环境, MODE_SANDBOX:测试环境
                'mode' => Pay::MODE_NORMAL,
            ],
        ],
        'logger' => [
            'enable' => false,
            'file' => './logs/pay.log',
            'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
            'type' => 'single', // optional, 可选 daily.
            'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
        ],
        'http' => [ // optional
            'timeout' => 5.0,
            'connect_timeout' => 5.0,
            // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
        ],
    ];

    /**
     * 小程序支付
     * @param $data
     * @return array
     */
    public function to_pay($data,$conf = [])
    {
        \Illuminate\Support\Facades\Log::info('支付信息',$data);
        \Illuminate\Support\Facades\Log::info('支付信息'.$data['pay_price']*100);
        $config = array_merge($this->config['wechat']['default'],$conf);
        $this->config['wechat']['default'] = $config;
        Pay::config($this->config);
        $order = [
            'out_trade_no' => $data['order_no'],
            'description' => $data['description'],
            'amount' => [
                //'total' => 10000*100,
                'total'=>$data['pay_price']*100,
                'currency' => 'CNY',
            ],
            'payer' => [
                'openid' => $data['openid'],
            ]
        ];
            // var_dump($order);
            $pay = Pay::wechat()->mini($order);
            return [
                'timeStamp'=>$pay->timeStamp,
                'nonceStr'=>$pay->nonceStr,
                'package'=>$pay->package,
                'signType'=>$pay->signType,
                'paySign'=>$pay->paySign,
                'app_id'=>'wx7d18bd50f621bf1c'
            ];

    }

    public function notify()
    {
        $pay = Pay::wechat($this->config);

        try{
            $data = $pay->verify(); // 是的，验签就这么简单！

            Log::debug('Wechat notify', $data->all());
        } catch (\Exception $e) {
            // $e->getMessage();
        }

        return $pay->success()->send();// laravel 框架中请直接 `return $pay->success()`
    }

    /**
     * @param array $data
     * @return void
     */
    public function wechatPayNotice(array $data)
    {
        $pay = Pay::config($this->config);

        // 是的，你没有看错，就是这么简单！
        $result = Pay::wechat()->callback();
        \Illuminate\Support\Facades\Log::info('1111',[$result->event_type]);
        \Illuminate\Support\Facades\Log::info('222',[$result->resource['ciphertext']['out_trade_no']]);
        \Illuminate\Support\Facades\Log::info('3333',[$result->resource['ciphertext']['trade_state']]);
        if($result->event_type=='TRANSACTION.SUCCESS' && $result->resource['ciphertext']['trade_state']=='SUCCESS'){
            $order_no = $result->resource['ciphertext']['out_trade_no'];
            //获取订单信息
            $order_query = TongOrder::query()->where('order_no',$order_no)->where('status',0);
            if(!$order_query->exists()){
                // 订单不存在
                return $pay->success();
            }
            $order_info = $order_query->first();
            //订单存在将订单状态修改成为支付成功
//            $order_query->update([
//                'status'=>1,//支付成功
//                'pay_status'=>1, //支付方式微信支付
//                'pay_time'=>date('Y-m-d H:i:s',time()) //订单的支付时间
//            ]);

            DB::beginTransaction();
            try {
                $TongOrderModel = TongOrder::query();
                $TongUserModel = TongUser::query();
                $TongUserProfitModel = TongUserProfit::query();

                //获取用户信息
                $user_info = $TongUserModel->where('id',$order_info['u_id'])->first();

                $old_identity_id = $user_info['identity_id'];

                //修改订单状态
                $order_query->update([
                    'status'=>1,//支付成功
                    'pay_status'=>1, //支付方式微信支付
                    'pay_time'=>date('Y-m-d H:i:s',time()) //订单的支付时间
                ]);
                //记录流水
                $TongUserProfitModel->create([
                    'u_id'=>$user_info['id'],
                    'order_id'=>$order_info['id'],
                    'money'=>-$order_info['order_price'],
                    'type'=>1, //订单
                    'symbol'=>2, //支出
                    'status'=>1,//已到账
                    'remark'=>'购买商品扣除'
                ]);
                //只有会员商品才会参与反润
                //用户的业绩统计
                user_statistics_order($user_info['id'],$order_info['order_price']);
                //只有会员商品才会参与反润
                if($order_info['order_type']==1 && ($order_info['order_goods_info']!==null && $order_info['order_goods_info']['is_shop_goods']==0)){
//                if(isSmallToBig($order_info['id'])){
//                    price_difference_upgrade_tow($user_info['id'],$order_info['id']);
//                }else{
//                    //自己购买商品补差价升级
//                    price_difference_upgrade($user_info['id'],$order_info['id']);
//                }
                    //price_difference_upgrade($user_info['id'],$order_info['id']);
                    price_difference_upgrade($user_info['id'],$order_info['id']);
                    leaderReward($user_info['id'],$order_info['id']); //每个新单给领导奖励
                    //调用自动升级（邀请团队业绩）
                    //userUpgrade($user_info['id']);
                    //商品的复购津贴
                    $new_user_info = RedisService::hGet($user_info['id']);
                    if($old_identity_id==$new_user_info['identity_id']){
                        new_user_fugou($user_info['id'],$order_info['id']);
                        leaderReward($user_info['id'],$order_info['id']); //每个新单给领导奖励
                        new_area_money($user_info['id'],$order_info['id']);
                    }

                    //公司的区域津贴
                    //area_money($order_info['u_id'],$order_info['id']);
                    new_area_money($user_info['id'],$order_info['id']);
                }elseif ($order_info['order_goods_info']['is_shop_goods']==2){
                    //会员专享的商品
                    //商品的复购津贴
                    //repurchase_money($order_info['id']);
                    new_user_fugou($user_info['id'],$order_info['id']);
                    leaderReward($user_info['id'],$order_info['id']); //每个新单给领导奖励
                    new_area_money($user_info['id'],$order_info['id']);
                }

                DB::commit();
                return true;
            }catch (\Exception $e){
                DB::rollBack();
                throw new DaoException(ResponseEnum::DAO_ERROR,$e->getMessage());
            }

            return $pay->success();
        }
    }

    /**
     * 用户充值的回调
     * @return void
     */
    public function wechatRechargeNotice()
    {
        $config = array_merge($this->config['wechat']['default'],['notify_url'=>'https://dztxs01.19w.top/api/wechat_pay_recharge_notice']);
        $this->config['wechat']['default'] = $config;
        $pay = Pay::config($this->config);
        $result = Pay::wechat()->callback();

        \Illuminate\Support\Facades\Log::info('充值回调1111',[$result->event_type]);
        \Illuminate\Support\Facades\Log::info('充值回调222',[$result->resource['ciphertext']['out_trade_no']]);
        \Illuminate\Support\Facades\Log::info('充值回调3333',[$result->resource['ciphertext']['trade_state']]);

        if($result->event_type=='TRANSACTION.SUCCESS' && $result->resource['ciphertext']['trade_state']=='SUCCESS'){
            $order_no = $result->resource['ciphertext']['out_trade_no'];
            //获取订单信息
            $order_query = TongUserRecharge::query()->where('order_no',$order_no)->where('status',1);
            if(!$order_query->exists()){
                // 订单不存在
                return $pay->success();
            }
            $order_info = $order_query->first();
            \Illuminate\Support\Facades\Log::info('获取到的订单信息',$order_info->toArray());
            //订单存在将订单状态修改成为支付成功
            DB::transaction(function () use($order_query,$order_info) {
                $order_query->update([
                    'status'=>2,//支付成功
                    'pay_time'=>date('Y-m-d H:i:s',time()) //订单的支付时间
                ]);
                $user_info = TongUser::query()->where('id',$order_info['u_id'])->first();
                $pre = $user_info['money'];
                TongUser::query()->where('id',$order_info['u_id'])->increment('money',$order_info['money']);

                TongUserProfit::query()->create([
                    'u_id'=>$order_info['u_id'],
                    'r_order_id'=>$order_info['id'],
                    'money'=>$order_info['money'],
                    'type'=>11,
                    'symbol'=>1,
                    'status'=>1,
                    'remark'=>'钱包充值到账',
                    'befor_money'=>$pre,
                    'after_money'=>bcadd($pre,$order_info['money'],2),
                ]);
            });

            return $pay->success();
        }
    }


    /**
     * 微信支付查询
     * @param $order_no
     * @param $mchid
     * @return mixed
     * @throws \Yansongda\Pay\Exception\ContainerException
     */
    public function order_query($order_no,$mchid){
        $config = array_merge($this->config['wechat']['default'],['mch_id'=>$mchid]);
        $this->config['wechat']['default'] = $config;
        Pay::config($this->config);

        $order = [
            'out_trade_no' => $order_no,
            '_action' => 'mini', // 查询小程序支付
            // '_action' => 'jsapi', // 默认为 jsapi
            // '_action' => 'app', // 查询 App 支付
            // '_action' => 'h5', // 查询 H5 支付
            // '_action' => 'mini', // 查询小程序支付
            // '_action' => 'native', // 查询 Native 支付
            // '_action' => 'combine', // 查询合单支付
        ];

        $pay_result = Pay::wechat()->query($order);
        $pay_result = $pay_result->toArray();
        return $pay_result;
//        echo $pay_result['trade_state'];
//        echo $pay_result['trade_state_desc'];
//        echo $pay_result['amount']['total'];
//        dd($pay_result);
    }


    /**
     *微信支付退款
     * @return array|bool
     */
    public function wechatPayRefund($order_no,$mchid){
        $pay_result = $this->order_query($order_no,$mchid);
        if($pay_result['trade_state']!='SUCCESS'){
            return false;
        }
        $config = array_merge($this->config['wechat']['default'],['mch_id'=>$pay_result['mchid'],'notify_url'=>'https://dztxs01.19w.top/api/wechat_refund_order']);
        $this->config['wechat']['default'] = $config;
        Pay::config($config);

        $order = [
            'out_trade_no' => $order_no,
            'out_refund_no' => 're'.time(),
            'amount' => [
                'refund' => $pay_result['amount']['total'],
                'total' => $pay_result['amount']['total'],
                'currency' => 'CNY',
            ],
            '_action' => 'mini', // 小程序退款
            // '_action' => 'jsapi', // jsapi 退款，默认
            // '_action' => 'app', // app 退款
            // '_action' => 'combine', // 合单退款
            // '_action' => 'h5', // h5 退款
            // '_action' => 'mini', // 小程序退款
            // '_action' => 'native', // native 退款

        ];
        $result = Pay::wechat()->refund($order);
        $result = $result->toArray();
        return $result;
        //dd($result);
    }

    function wechatRefundOrder(){
        //return $pay->success();
    }

}
